<template>
  <a-table
    rowKey="id"
    size="middle"
    bordered
    :loading="loading"
    :columns="columns"
    :dataSource="tableDataWithTotals"
    :pagination="false"
  >
    <template slot="htmlSlot" slot-scope="text">
      <div v-html="text"></div>
    </template>

    <template slot="imgSlot" slot-scope="text,record">
      <div style="font-size: 12px;font-style: italic;">
        <span v-if="!text">无图片</span>
        <img v-else :src="getImgView(text)" :preview="record.id" alt="" style="max-width:80px;height:25px;"/>
      </div>
    </template>

    <template slot="fileSlot" slot-scope="text">
      <span v-if="!text">无文件</span>
      <a-button
        v-else
        ghost
        type="primary"
        icon="download"
        size="small"
        @click="downloadFile(text)"
      >
        <span>下载</span>
      </a-button>
    </template>
  </a-table>
</template>

<script>
import { getAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'

export default {
  name: 'CwXmzcsrbSubTable',
  mixins: [JeecgListMixin],
  props: {
    record: {
      type: Object,
      default: null,
    }
  },
  data() {
    return {
      description: '项目支出收入支出表内嵌列表',
      disableMixinCreated: true,
      loading: false,
      dataSource: [],
      // 需要计算合计的收支字段（共6个）
      totalFields: [
        'snjz', 'financialFund', 'undertakingRevenue',
        'otherRevenue', 'fczbkjy', 'projectExpenditure'
      ],
      // 按“财政非财政”字段分类的标识
      financeMap: {
        financial: '财政', // 财政非财政=财政
        nonFinancial: '非财政' // 财政非财政=非财政
      },
      columns: [
        {
          title: '项目',
          align: 'center',
          dataIndex: 'project',
        },
        {
          title: '财政非财政',
          align: 'center',
          dataIndex: 'czFcz_dictText'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '年度',
          align: 'center',
          dataIndex: 'year_dictText'
        },
        // 收支字段添加格式化（保留2位小数，适配金额数据）
        {
          title: '上年结转',
          align: 'center',
          dataIndex: 'snjz',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '财政资金',
          align: 'center',
          dataIndex: 'financialFund',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '事业收入',
          align: 'center',
          dataIndex: 'undertakingRevenue',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '其他收入',
          align: 'center',
          dataIndex: 'otherRevenue',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '非财政拨款结余',
          align: 'center',
          dataIndex: 'fczbkjy',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '--年项目支出',
          align: 'center',
          dataIndex: 'projectExpenditure',
          customRender: (text) => this.formatNumber(text)
        },
        {
          title: '备注',
          align: 'center',
          dataIndex: 'remark',
          scopedSlots: { customRender: 'htmlSlot' }
        },
      ],
      url: {
        listByMainId: '/cw/cwXmzcsrbTj/queryCwXmzcsrbByMainId',
      },
    }
  },
  computed: {
    // 带两条分类合计行的完整数据
    tableDataWithTotals() {
      if (!this.dataSource || this.dataSource.length === 0) return []

      // 深拷贝原始数据，避免污染原数据
      const newData = JSON.parse(JSON.stringify(this.dataSource))
      // 分别计算“财政”和“非财政”的收支合计
      const financialTotals = this.calcFinanceTotals(this.financeMap.financial)
      const nonFinancialTotals = this.calcFinanceTotals(this.financeMap.nonFinancial)

      // 构建“财政合计”行
      const financialTotalRow = this.buildTotalRow('财政合计', financialTotals)
      // 构建“非财政合计”行
      const nonFinancialTotalRow = this.buildTotalRow('非财政合计', nonFinancialTotals)

      // 添加两条合计行到表格底部
      newData.push(financialTotalRow, nonFinancialTotalRow)
      return newData
    }
  },
  watch: {
    record: {
      immediate: true,
      handler() {
        if (this.record) {
          this.loadData(this.record)
        }
      }
    }
  },
  methods: {
    loadData(record) {
      this.loading = true
      this.dataSource = []
      getAction(this.url.listByMainId, { id: record.id })
        .then((res) => {
          if (res.success) {
            this.dataSource = res.result.records || [] // 兼容无数据场景
          }
        })
        .finally(() => {
          this.loading = false
        })
    },

    /**
     * 数字格式化方法（金额默认保留2位小数）
     */
    formatNumber(text) {
      const num = Number(text)
      return isNaN(num) ? '0.00' : num.toFixed(2)
    },

    /**
     * 按“财政非财政”分类计算收支合计
     * @param financeType 分类值（财政/非财政）
     */
    calcFinanceTotals(financeType) {
      // 初始化合计为0
      const totals = this.totalFields.reduce((obj, field) => {
        obj[field] = 0
        return obj
      }, {})

      // 筛选对应分类的数据并累加收支字段
      this.dataSource.forEach(item => {
        if (item.czFcz_dictText === financeType) { // 匹配“财政”或“非财政”
          this.totalFields.forEach(field => {
            const val = Number(item[field])
            totals[field] += isNaN(val) ? 0 : val
          })
        }
      })

      // 格式化合计结果（保留2位小数）
      this.totalFields.forEach(field => {
        totals[field] = totals[field].toFixed(2)
      })

      return totals
    },

    /**
     * 构建分类合计行
     * @param label 合计行标签（财政合计/非财政合计）
     * @param totals 对应分类的合计数据
     */
    buildTotalRow(label, totals) {
      const totalRow = {
        id: `total_${label}_${new Date().getTime()}`, // 唯一ID，避免rowKey重复警告
        project: label, // 项目列显示合计标签
        czFcz_dictText: '', // 分类列留空
        unit_dictText: '',
        year_dictText: '',
        remark: '',
        // 填充收支字段合计值
        snjz: totals.snjz,
        financialFund: totals.financialFund,
        undertakingRevenue: totals.undertakingRevenue,
        otherRevenue: totals.otherRevenue,
        fczbkjy: totals.fczbkjy,
        projectExpenditure: totals.projectExpenditure
      }
      return totalRow
    },

    // 空实现方法，避免报错
    downloadFile(text) {
    },
    getImgView(text) {
      return text
    }
  },
}
</script>

<style scoped>
/* 合计行样式优化，两条行区分显示 */
::v-deep .ant-table-tbody tr:nth-last-child(2),
::v-deep .ant-table-tbody tr:last-child {
  background-color: #f5fafe !important;
  font-weight: 600 !important;
  text-align: center !important;
  white-space: nowrap !important;
}

/* 财政合计行样式 */
::v-deep .ant-table-tbody tr:nth-last-child(2) {
  border-top: 2px solid #10b981 !important;
  color: #059669 !important;
}

/* 非财政合计行样式 */
::v-deep .ant-table-tbody tr:last-child {
  border-top: 1px solid #6ee7b7 !important;
  color: #047857 !important;
}

/* 表格横向滚动和列宽优化，适配11列表格 */
::v-deep .ant-table-wrapper {
  overflow-x: auto !important;
  min-width: 1200px !important;
}

::v-deep .ant-table-column-title {
  white-space: nowrap !important;
  font-size: 12px !important;
  padding: 8px 6px !important;
}

::v-deep .ant-table-tbody td {
  white-space: nowrap !important;
  font-size: 12px !important;
  padding: 8px 6px !important;
}

::v-deep .ant-table-thead th {
  white-space: nowrap !important;
}
</style>